package cn.xaut.数组;

public class demo209 {

    // 滑动窗口
    public int minSubArrayLen(int target, int[] nums) {

        int len = nums.length;
        if (len <= 0)
            return 0;
        if (len == 1)
            return target == nums[0] ? 1 : 0;

        int l = 0, r = 1;
        if (nums[l] >= target)
            return 1;
        int res = len + 1;
        int sum = nums[l] + nums[r];
        while (true) {

            if (sum < target) {
                r ++;
                if (r == len)
                    return res == len + 1 ? 0 : res;
                sum += nums[r];
            } else {    // sum >= target
                res = Math.min(res, r - l + 1);
                sum -= nums[l];
                l ++;
            }
        }
        
    }

    // 另一种写法
    public int minSubArrayLen2(int target, int[] nums) {

        int len = nums.length;

        int l = 0, r = -1;
        int res = len + 1;
        int sum = 0;
        while (l < len) {

            if (sum < target) {
                r ++;
                if (r == len)
                    return res == len + 1 ? 0 : res;
                sum += nums[r];
            } else {    // sum > target
                res = Math.min(res, r - l + 1);
                sum -= nums[l];
                l ++;
            }
        }
        return res;
    }
}
